<template>
	<div style="padding: 14px">
		<el-form>
			<el-row :gutter="24">
				<el-col :span="6">
					<el-form-item label="模型版本">
						<el-select v-model="from.currentModel"  placeholder="请选择" @change="switchModel">
							<el-option v-for="item in modelList" :key="item" :label="item" :value="item"/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item :label="`置信度`">
						<div style="display: flex; align-items: center; width: 100%;">
							<el-slider style="flex: 1; margin-right: 1rem;"  v-model="from.confidence" :max="1" :min="0.1" :step="0.01"/>
							<span>{{from.confidence}}</span>
						</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>

		<el-row :gutter="24">
			<el-col>
				<el-form-item label="显示类型">
					<el-checkbox-group v-model="from.show_category">
						<el-checkbox
							v-for="item in modelInfos"
							:key="item"
							:label="item"
						>
							{{translate(item)}}
						</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
			</el-col>
		</el-row>

		<el-card>
			<div style="display: flex; align-items: center;">
				<el-upload :show-file-list="false" style="width: 500px;" ref="upload" class="upload-demo"  action="/api/yolo_model/uploadImage/" :on-success="handleUploadSuccess" :data="uploadFormData" drag multiple :limit="1" :on-exceed="handleExceed">
					<el-icon class="el-icon--upload"> <upload-filled/> </el-icon>
					<div class="el-upload__text"> 拖拽文件到这 / <em>点击上传</em> </div>

				</el-upload>
				<div style="flex: 1; display: flex; align-items: center; justify-content: space-evenly">
					<template v-if="currentImgResult.result_image">
						<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: 16px; font-weight: 600;">
							<span>原始图像</span>
							<el-image :preview-src-list="['/api' + currentImgResult.upload_image]" :src="'/api' + currentImgResult.upload_image" style="width: 300px; height: 300px; border: 1px solid #409eff; margin-left: 8px;"/>
						</div>
						<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: 16px; font-weight: 600;">
							<span>识别结果</span>
							<el-image :preview-src-list="['/api' + currentImgResult.result_image]" :src="'/api' + currentImgResult.result_image" style="width: 300px; height: 300px; border: 1px solid #409eff; margin-left: 8px;"/>
						</div>
					</template>
					<el-empty v-else description="暂无识别结果"></el-empty>
				</div>
			</div>
		</el-card>

		<el-table :data="currentImgResult.bboxes" border style="margin-top: 20px;" v-if="currentImgResult.bboxes">
			<el-table-column type="index"/>
			<el-table-column label="识别类型" prop="category">
				<template #default="{row}">
					{{translate(row.category)}}
				</template>
			</el-table-column>
			<el-table-column label="置信度" prop="confidence" align="center">
				<template #default="{row}">
					<el-progress :percentage="(row.confidence * 100).toFixed(2)" :stroke-width="20" :color="[
						{color: '#67C23A', percentage: 100},
						{color: '#409EFF', percentage: 80},
						{color: '#00aed1', percentage: 60},
						{color: '#E6A23C', percentage: 40},
						{color: '#F56C6C', percentage: 20},
					]"/>
				</template>
			</el-table-column>
			<el-table-column label="高度" prop="bbox_h"/>
			<el-table-column label="宽度" prop="bbox_w"/>
			<el-table-column label="x轴坐标" prop="bbox_x"/>
			<el-table-column label="y轴坐标" prop="bbox_y"/>
		</el-table>
		<el-empty v-else description="暂无记录!"></el-empty>
	</div>
</template>
<script setup lang="ts">
import {modelVersions, changeModel, yoloModelInfo} from "/@api/yolo_model/hz-system-yolo-model-api";
import {UploadFilled} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox, genFileId, UploadInstance, UploadProps, UploadRawFile} from "element-plus";
import {computed, ref} from "vue";
import {useMessage} from "/@hooks/message";
import {translate} from '/@/utils/translate'
import {useRouter} from 'vue-router'
import {getSearchResults} from "/@api/encyclopedia";
const router = useRouter()
//图片上传参数
const from = ref({
	currentModel: '',
	confidence: 0.5,
	show_category: []
})
const uploadFormData = computed(() => ({
	currentModel: from.value.currentModel,
	confidence: from.value.confidence,
	show_category: from.value.show_category.join(',')
}))
//切换模型
const switchModel = async (model) => {
	const res = await changeModel(model)
	ElMessage({
		type: res.code == 200 ? 'success' : 'error',
		message: res.msg,
		duration: 2000
	})
}
//显示识别类型
const modelInfos = ref([])
//获取模型下拉
const modelList = ref([])
const getModelVersions = async () => {
	const res = await modelVersions()
	modelList.value = res.data.model_version
	from.value.currentModel = modelList.value[0]


	const infoRes = await yoloModelInfo()
	modelInfos.value = Object.values(infoRes.data.supported_classes)
	from.value.show_category = [...modelInfos.value]
}
getModelVersions()

//当前上传图片的返回结果
const currentImgResult = ref({})
//图片(自动)上传成功调用
const handleUploadSuccess = async (res: any, file: any, fileList: any) => {
	if(res.code !== 200){
		useMessage().error(res.msg)
		return
	}
	currentImgResult.value = res.data

	if (currentImgResult.value.bboxes.length >= 1) {
		//查询是否有百科数据
		const keyword = currentImgResult.value.bboxes[0].category
		const result = await getSearchResults({keyword})
		const total = result.data.total
		if (total > 0){
			ElMessageBox.confirm(
				`识别成功, 查询到${total}可能相关数据,是否前往查看?`,
				'提示',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			).then(() => {
				router.push({
					path: `/search`,
					query: {
						page: 1,
						keyword
					},
				})
			})
		}else if(total == 0){
			let userInfo = window.localStorage.getItem('userInfo')
			userInfo = userInfo ? JSON.parse(userInfo) : {}
			userInfo = userInfo.userInfo
			if(userInfo?.is_superuser){
				ElMessageBox.confirm(
					`识别成功, 关键词 【${keyword}】 未查询到相关百科数据,是否前往添加?`,
					'提示',
					{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					}
				).then(() => {
					window.localStorage.setItem('temp_add_baike_title', keyword)
					console.log(keyword)
					router.push({
						path: `/index`,
						query: {
							component: '百科管理'
						},
					})
				})
			}
		}
	}
	if(currentImgResult.value.bboxes.length == 0){
		useMessage().warning('未识别到任何物体')
	}
}

const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
	upload.value!.clearFiles()
	const file = files[0] as UploadRawFile
	file.uid = genFileId()
	upload.value!.handleStart(file)
	// 执行上传
	upload.value!.submit()
}

</script>
<style scoped lang="scss">
.yolo-main{
	width: 100%;
	display: flex;
	div{
		flex: 1;
	}
}
</style>
